import pymongo
import os.path
import time
import model.config as config

class requestMongo(object):
    # init
    def __init__(self, mongoIP='test_ip', db="local"):
        config_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        config_path += "\data\ServiceMode.ini"
        cr = config.ConfigReader(config_path)
        test_mongo = cr.get('MongoDB', mongoIP)
        self.myclient = pymongo.MongoClient("mongodb://%s:27017" % test_mongo)
        self.mydb = self.myclient[db]
        print(self.mydb)

    # find 仅查找  field2 且field1 = values 的值
    def find_one(self, tableName, field1, values, field2):
        self.mytable = self.mydb[tableName]
        print("find table name ======%s" % self.mytable)
        self.find = self.mytable.find_one({field1: values}, {field2: 1})
        return self.find

    # finds 查找field = values 一行的数据
    def finds(self, tableName, field, values):
        self.mytable = self.mydb[tableName]
        self.finds = self.mytable.find_one({field: values})
        return self.finds

    def update_one(self, tableName, field, field_values, after, after_values):
        self.mytable = self.mydb[tableName]
        update_before = {field: field_values}
        f_result = self.mytable.find_one(update_before)
        f_result[after] = after_values
        self.update = self.mytable.update_one(update_before, {'$set': f_result})
        return self.update

    def __del__(self):
        self.myclient.close()
#
#
#
